<template>
  <div class="app-container">
    <el-card class="box-card">
      <div class="table">
        <div class="addUser">
          <el-button
            class="el-icon-folder-add"
            type="primary"
            @click="addDialog"
            >新增</el-button
          >
        </div>
        <el-table
          v-loading="listLoading"
          :data="tableData"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row
        >
          <el-table-column align="center" type="index" label="序号">
          </el-table-column>
          <el-table-column
            label="名称"
            align="center"
            prop="title"
          ></el-table-column>
          <el-table-column label="作者" align="center" prop="author">
          </el-table-column>
          <el-table-column label="封面" align="center">
            <template slot-scope="scope">
              <el-image
                :src="scope.row.cover"
                style="width: 80px"
                :preview-src-list="[scope.row.cover]"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column label="类别" align="center" prop="category_id">
            <template slot-scope="scope">
              <div>
                <el-tag type="primary" v-if="scope.row.category_id === 0"
                  >科幻</el-tag
                >
                <el-tag type="primary" v-else-if="scope.row.category_id === 1"
                  >历史</el-tag
                >
                <el-tag type="primary" v-else-if="scope.row.category_id === 2"
                  >文学</el-tag
                >
                <el-tag type="primary" v-else-if="scope.row.category_id === 3"
                  >科普</el-tag
                >
                <el-tag type="primary" v-else-if="scope.row.category_id === 4"
                  >经济</el-tag
                >
                <el-tag type="primary" v-else-if="scope.row.category_id === 5"
                  >文化</el-tag
                >
                <el-tag type="primary" v-else-if="scope.row.category_id === 6"
                  >政治</el-tag
                >
                <el-tag type="primary" v-else-if="scope.row.category_id === 7"
                  >人文</el-tag
                >
                <el-tag type="primary" v-else-if="scope.row.category_id === 8"
                  >社会</el-tag
                >
                <el-tag type="primary" v-else-if="scope.row.category_id === 9"
                  >启蒙</el-tag
                >
                <el-tag type="primary" v-else>军事</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="简介"
            align="center"
            prop="intro"
            width="100px"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column label="评价" align="center" prop="score">
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="create_time">
          </el-table-column>
          <el-table-column
            label="备注"
            :show-overflow-tooltip="true"
            align="center"
            prop="other"
          >
          </el-table-column>
          <el-table-column align="center" label="操作" width="250">
            <template slot-scope="scope">
              <el-button
                class="el-icon-view"
                type="primary"
                size="mini"
                @click="queryInfo(scope.row)"
                >查看</el-button
              >

              <el-button
                class="el-icon-edit"
                type="warning"
                size="mini"
                @click="editDialog(scope.row)"
                >修改</el-button
              >
              <el-button
                class="el-icon-folder-delete"
                type="danger"
                size="mini"
                @click="delInfo(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="pageBox">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :page-size="pageOption.pageNum"
          :total="pageOption.total"
          :current-page="pageOption.pageSize"
          @current-change="pageJump"
          @prev-click="pageOption.pageSize--"
          @next-click="pageOption.pageSize++"
        ></el-pagination>
      </div>
      <div class="bookFormData">
        <el-dialog
          :title="dialogOption.title"
          :visible.sync="dialogOption.visible"
          width="60%"
          :modal-append-to-body="false"
        >
          <el-form ref="formData" :model="formData" label-width="80px">
            <el-row>
              <el-col :span="8">
                <el-form-item
                  label="书籍名称："
                  prop="title"
                  :label-width="formLabelWidth"
                  :rules="formRules.required"
                >
                  <el-input
                    :readonly="dialogOption.required"
                    v-model="formData.title"
                    :disabled="dialogOption.disabled"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="书籍作者："
                  prop="author"
                  :label-width="formLabelWidth"
                  :rules="formRules.required"
                >
                  <el-input
                    :readonly="dialogOption.required"
                    type="text"
                    v-model="formData.author"
                    :disabled="dialogOption.disabled"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="书籍类别："
                  prop="category_id"
                  :label-width="formLabelWidth"
                  :rules="formRules.required"
                >
                  <el-select
                    :readonly="dialogOption.required"
                    v-model="formData.category_id"
                    :disabled="dialogOption.disabled"
                    placeholder="请选择类别"
                    @change="SelectBookOrCategory"
                  >
                    <el-option
                      v-for="item in bookCategoryData"
                      :key="item.id"
                      :label="item.category_name"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="书籍简介" :label-width="formLabelWidth">
                  <el-input
                    type="textarea"
                    maxlength="200"
                    show-word-limit
                    :readonly="dialogOption.required"
                    v-model="formData.intro"
                    autocomplete="off"
                    :disabled="dialogOption.disabled"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item prop="details" class="contentStyle">
                  <TinyEditor v-model="formData.details" :IS="IS"></TinyEditor>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="书籍备注" :label-width="formLabelWidth">
                  <el-input
                    :readonly="dialogOption.required"
                    type="textarea"
                    placeholder="请输入内容"
                    v-model="formData.other"
                    maxlength="30"
                    show-word-limit
                    :disabled="dialogOption.disabled"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="书籍封面" :label-width="formLabelWidth">
                  <el-upload
                    class="cover-uploader"
                    :action="uploadUrl"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :disabled="dialogOption.disabled"
                  >
                    <img
                      v-if="formData.cover"
                      :src="formData.cover"
                      class="cover"
                    />
                    <i v-else class="el-icon-plus cover-uploader-icon"></i>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogOption.visible = false">取 消</el-button>
            <el-button
              type="primary"
              v-if="dialogOption.type === 1"
              @click="dialogOption.visible = false"
              >确 定</el-button
            >
            <el-button
              type="primary"
              v-if="dialogOption.type === 2"
              @click="editInfo"
              >修 改</el-button
            >
            <el-button
              class="el-icon-add"
              v-if="dialogOption.type === 3"
              type="warning"
              @click="addInfo"
              >新增</el-button
            >
          </div>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  getBookList,
  addBookInfo,
  delBookInfo,
  editBookInfo,
  editBookCategory,
} from '@/api/book'
import { getBookCategoryList } from '@/api/category'
import TinyEditor from '@/components/Tinymce'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger',
      }
      return statusMap[status]
    },
  },
  components: { TinyEditor },
  data() {
    return {
      uploadUrl: 'http://www.lengnuanit.top/api/upload/upload',
      // uploadUrl: "http://127.0.0.1:7001/api/upload/upload",
      formLabelWidth: '100px',
      formRules: this.$store.state.settings.formRules,
      tableData: null,
      listLoading: true,
      pageOption: {
        pageNum: 10,
        pageSize: 1,
        total: 1,
      },
      dialogOption: {
        title: '查看图书',
        type: 1,
        visible: false,
        required: false,
        disabled: false,
      },
      IS: false,
      formData: {
        title: '',
        author: '',
        score: '',
        intro: '',
        details: '',
        cover: '',
        other: '',
        category_id: null,
      },
      bookId: null,
      bookCategoryData: null,
    }
  },
  created() {
    // console.log(this.formRules);
    this.getData()
  },
  methods: {
    //获取图书分类
    getBookCategory() {
      getBookCategoryList({
        pageNum: 1000,
        pageSize: this.pageOption.pageSize,
      }).then((res) => {
        console.log(res)
        this.bookCategoryData = res.data
      })
    },
    //获取图书数据
    getData() {
      this.listLoading = true
      getBookList({
        pageNum: this.pageOption.pageNum,
        pageSize: this.pageOption.pageSize,
      }).then((res) => {
        // console.log(res);
        this.tableData = res.data
        this.pageOption.total = res.total
        this.listLoading = false
      })
    },
    //查看图书
    queryInfo(row) {
      //console.log(row);
      this.resetForm('formData')
      this.getBookCategory()
      this.formData = Object.assign({}, row)
      this.dialogOption.type = 1
      this.dialogOption.visible = true
      this.dialogOption.required = true
      this.dialogOption.disabled = true
      this.dialogOption.title = '查看图书'
    },
    //新增弹窗
    addDialog() {
      this.resetForm('formData')
      this.getBookCategory()
      this.formData = {}

      this.dialogOption.type = 3
      this.dialogOption.visible = true
      this.dialogOption.required = false
      this.dialogOption.disabled = false
      this.dialogOption.title = '新增图书'
    },
    //新增图书
    addInfo() {
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          addBookInfo(this.formData).then((res) => {
            //console.log(res);
            if (res.code == 200) {
              this.$message.success(res.msg)
              this.getData()
              this.dialogOption.visible = false
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    //修改弹窗
    editDialog(row) {
      //console.log(row);
      this.resetForm('formData')
      this.bookId = row.id
      this.getBookCategory()
      this.formData = Object.assign({}, row)
      this.dialogOption.type = 2
      this.dialogOption.visible = true
      this.dialogOption.required = false
      this.dialogOption.disabled = false
      this.dialogOption.title = '修改图书'
    },
    //修改图书
    editInfo() {
      editBookInfo({
        id: this.bookId,
        data: this.formData,
      }).then((res) => {
        //console.log(res);
        if (res.code == 200) {
          this.$message.success(res.msg)
          this.getData()
        } else {
          this.$message.error(res.msg)
        }
        this.dialogOption.visible = false
      })
    },
    //删除
    delInfo(row) {
      //console.log(row);
      this.$confirm(
        '此操作将删除' + row.title + '这条图书数据，是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          delBookInfo(row.id)
            .then((res) => {
              //console.log(res);
              if (res.code == 200) {
                this.$message.success(res.msg)
                this.getData()
              } else {
                this.$message.error(res.msg)
              }
            })
            .catch({})
        })
        .catch(() => {
          // this.$message.info("已取消");
        })
    },
    // 重置验证规则
    resetForm(formName) {
      // console.log(formName);
      if (this.$refs[formName] != undefined) {
        this.$refs[formName].resetFields()
      }
    },
    // 分页跳转
    pageJump(page) {
      //console.log(page);
      this.pageOption.pageSize = page
      this.getData()
    },
    //图片上传
    handleAvatarSuccess(res, file) {
      this.$set(this.formData, 'cover', res.data.url)
      //console.log(this.formData.cover);
    },
    //图片上传
    beforeAvatarUpload(file) {
      //console.log(file);
      const isType = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isType) {
        this.$message.error('上传头像图片只能是 JPG或PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isType && isLt2M
    },
    //图书关联分类
    SelectBookOrCategory(e) {
      console.log('BookID')
      console.log('分类ID', e)
      if (this.bookId) {
        let data = {
          category_id: e,
          book_id: this.bookId,
        }
        editBookCategory(data).then((res) => {
          console.log(res)
        })
      }
    },
  },
}
</script>
<style lang="scss" scope>
.addUser {
  padding: 0 0 20px 0;
}
.pageBox {
  text-align: right;
  padding: 10px 0 20px 0;
}
.cover-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.cover-uploader .el-upload:hover {
  border-color: #409eff;
}
.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.cover {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
